package com.dm.learn.java.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileTest {
	/*
	 * 复制文件夹包含其中的文件
	 */
	public static void copyDir(String sourceDir, String targetDir) {
		if (targetDir == null) {
			return;
		}
		File t = new File(targetDir);
		if (!t.canWrite()) {
			return;
		}
		t.mkdirs();

		File[] file = (new File(sourceDir)).listFiles();
		for (int i = 0; i < file.length; i++) {
			if (file[i].isFile()) {
				File sourceFile = file[i];
				File targetFile = new File(
						new File(targetDir).getAbsolutePath() + File.separator
								+ file[i].getName());
				copyFile(sourceFile, targetFile);
			} else if (file[i].isDirectory()) {
				String dir1 = sourceDir + File.separator + file[i].getName();
				String dir2 = targetDir + File.separator + file[i].getName();
				copyDir(dir1, dir2);
			}
		}
	}

	/**
	 * 复制文件
	 * 
	 * @param resource
	 *            -源文件
	 * @param target
	 *            -目标文件
	 */
	public static void copyFile(File source, File target) {
		if (source == null) {
			return;
		}
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(source));
			bos = new BufferedOutputStream(new FileOutputStream(target));
			byte[] b = new byte[1024 * 5];
			int length;
			while ((length = bis.read(b)) != -1) {
				bos.write(b, 0, length);
			}
			bos.flush();
		} catch (Exception e) {
			return;
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * @param
	 * @return void
	 * @throws
	 */
	public static void main(String[] args) {
		File file  = new File("D:\\EBT\\log");
		System.out.println(file.length());
		System.out.println(file.getPath());
		System.out.println(file.getParent());
	}

}
